#include "ex06aa.cpp"
#include "pwext.hpp"
#include <stdio.h>

class malloc_arena
{
public:
	malloc_arena() :
		total_(0)
	{ 
		fprintf(stderr, "creating malloc_arena %p\n", this);
	}

	~malloc_arena()
	{
		fprintf(stderr, "destroying malloc_arena %p\n", this);
	}

	// just for show, count the bytes and return the pointer to itself
	void *get_block(size_t bytes)
	{
		total_ += bytes;
		fprintf(stderr, "malloc_arena %p: total %d\n", this, (int)total_);
		return this;
	}

	size_t total_;
};

// copied from ex06ad
class malloc_arena; // its implementation is not important here

class our_malloc
{
public:
	void *malloc(size_t bytes)
	{
		return arena_.get_block(bytes);
	}

protected:
	malloc_arena arena_;
	// ... other definitions ...
};

pw::event startev;

// [[ex06af]]
// DEBUG descr Allocation of a separate context per thread.
class worker : public pw::pwthread
{
public:
	worker(our_malloc *malc) : 
		malc_(malc)
	{ }

	~worker()
	{
		delete malc_;
	}
	// DEBUG {
	void *execute()
	{
		startev.wait();
		for (int i = 0; i < 3; i++) {
			fprintf(stderr, "worker %p malloc_arena %p\n", this, malc_->malloc(10));
		}
		return 0;
	}
	// DEBUG }

protected:
	our_malloc *malc_;
};
// END

// DEBUG from

int main()
{
	worker w1(new our_malloc), w2(new our_malloc);

	w1.start();
	w2.start();

	startev.signal();

	w1.join();
	w2.join();

	return 0;
}

/* Sample output:
creating malloc_arena 0x7bc010
creating malloc_arena 0x7bc030
malloc_arena 0x7bc010: total 10
worker 0x7fff19988280 malloc_arena 0x7bc010
malloc_arena 0x7bc010: total 20
worker 0x7fff19988280 malloc_arena 0x7bc010
malloc_arena 0x7bc010: total 30
worker 0x7fff19988280 malloc_arena 0x7bc010
malloc_arena 0x7bc030: total 10
worker 0x7fff19988230 malloc_arena 0x7bc030
malloc_arena 0x7bc030: total 20
worker 0x7fff19988230 malloc_arena 0x7bc030
malloc_arena 0x7bc030: total 30
worker 0x7fff19988230 malloc_arena 0x7bc030
destroying malloc_arena 0x7bc030
destroying malloc_arena 0x7bc010
*/
